#include "main.h"

CAN_MSG   CANFIFOBuffer[16];//定义CAN消息缓冲区，深度值必须是2的n次方
CAN_BUFFER  CANRxBuffer[2];

void CAN_BUF_Init(uint8_t Channel)
{
  CANRxBuffer[Channel].BufferSize = 16;
  CANRxBuffer[Channel].pBuffer = CANFIFOBuffer;
  CANRxBuffer[Channel].ReadIndex = 0;
  CANRxBuffer[Channel].WriteIndex = 0;
  CANRxBuffer[Channel].GotMsgNum = 0;
}

//获取当前正在接收数据帧
CAN_MSG *CAN_BUF_PickMsg(uint8_t Channel)
{
  return &CANRxBuffer[Channel].pBuffer[CANRxBuffer[Channel].WriteIndex];
}
//表示成功读取到一帧数据
void CAN_BUF_ApendMsg(uint8_t Channel)
{
  __set_PRIMASK(1);
  CANRxBuffer[Channel].WriteIndex = (++CANRxBuffer[Channel].WriteIndex)&(CANRxBuffer[Channel].BufferSize-1);//写缓冲区递增
  //判断缓冲区是否已满
  if(CANRxBuffer[Channel].WriteIndex==CANRxBuffer[Channel].ReadIndex){
    CANRxBuffer[Channel].ReadIndex = (++CANRxBuffer[Channel].ReadIndex)&(CANRxBuffer[Channel].BufferSize-1);//读缓冲区递增
  }else{
    CANRxBuffer[Channel].GotMsgNum++; //有效数据加1
  }
  __set_PRIMASK(0);
}

void CAN_BUF_PushMsg(uint8_t Channel,CAN_MSG CANMsg)
{
  CAN_MSG *pMsg = CAN_BUF_PickMsg(Channel);
  *pMsg = CANMsg;
  CAN_BUF_ApendMsg(Channel);
}

//获取成功读到的消息
int CAN_BUF_PopMsg(uint8_t Channel,CAN_MSG **pMsg,uint8_t MsgLen)
{
  __set_PRIMASK(1);
  int MsgNum = ((CANRxBuffer[Channel].WriteIndex>=CANRxBuffer[Channel].ReadIndex)?CANRxBuffer[Channel].GotMsgNum:(CANRxBuffer[Channel].BufferSize-CANRxBuffer[Channel].ReadIndex));
  *pMsg = &CANRxBuffer[Channel].pBuffer[CANRxBuffer[Channel].ReadIndex];
  MsgNum = (MsgNum<MsgLen)?MsgNum:MsgLen;//根据需要返回的帧数调整实际返回帧数
  CANRxBuffer[Channel].GotMsgNum -= MsgNum;
  CANRxBuffer[Channel].ReadIndex = (CANRxBuffer[Channel].ReadIndex+MsgNum)&(CANRxBuffer[Channel].BufferSize-1);
  __set_PRIMASK(0);
  return MsgNum;
}

